from fastapi import APIRouter, Depends, Request, Form, Query
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session
from auth.db import SessionLocal
from auth.models import User
from auth.utils import get_current_user_info
from fastapi.templating import Jinja2Templates
from ecg.models import ECGRecord
router = APIRouter()
templates = Jinja2Templates(directory="templates")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# ---------------- 用户管理页 ----------------
@router.get("/users", response_class=HTMLResponse)
def user_manage(request: Request, db: Session = Depends(get_db), q: str = Query(None)):
    username, role = get_current_user_info(request)
    if not username or role != "admin":
        return RedirectResponse(url="/", status_code=303)

    query = db.query(User)
    if q:
        query = query.filter(User.username.contains(q))
    users = query.all()

    return templates.TemplateResponse(
        "dashboard.html",
        {
            "request": request,
            "username": username,
            "role": role,
            "active_tab": "users",
            "users": users,
            "search_q": q or ""
        }
    )

# ---------------- 修改用户角色 ----------------
@router.post("/users/update_role")
def update_user_role(request: Request, username: str = Form(...), role: str = Form(...), db: Session = Depends(get_db)):
    current_user, current_role = get_current_user_info(request)
    if not current_user or current_role != "admin":
        return RedirectResponse(url="/", status_code=303)

    user = db.query(User).filter(User.username == username).first()
    if user:
        user.role = role
        db.commit()

    return RedirectResponse(url="/users", status_code=303)

# ---------------- 删除用户 ----------------
@router.get("/users/delete/{username}")
def delete_user(username: str, request: Request, db: Session = Depends(get_db)):
    current_user, role = get_current_user_info(request)
    if not current_user or role != "admin":
        return RedirectResponse(url="/", status_code=303)

    if username == current_user:
        return RedirectResponse(url="/users?msg=删除", status_code=303)

    user = db.query(User).filter(User.username == username).first()
    if user:
        db.delete(user)
        db.commit()

    return RedirectResponse(url="/users", status_code=303)
